package cn.tedu.ivos.base.security;

import cn.tedu.ivos.base.response.JsonResult;
import cn.tedu.ivos.base.response.StatusCode;
import cn.tedu.ivos.user.mapper.UserMapper;
import cn.tedu.ivos.user.pojo.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;



@Slf4j
@Service
public class CustomAuthenticationSuccessHandler
        implements AuthenticationSuccessHandler {
    @Autowired
    UserMapper userMapper;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request
            , HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException {
        //响应一个JsonResult
        log.debug("认证成功，响应JsonResult");
//        JsonResult result = new JsonResult(StatusCode.LOGIN_SUCCESS);
        // 设置状态码  msg  数据 UserVO--->认证 用户名称和密码---》可以根据认证用户名查询该用户
        String username = authentication.getName();
        UserVO userVO = userMapper.selectByUsername(username);
//        result.setData(userVO);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
//        response.getWriter().write(JSON.toJSONString(result));
        response.getWriter().write(JSON.toJSONString(JsonResult.ok(userVO)));
    }
}
